package com.cl.ks.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;
import org.apache.commons.compress.utils.Lists;

import java.util.ArrayList;
import java.util.List;


/**
 * @author chenyitao
 * @date 2021/5/18
 */
public class SqlConvert {

    public static final String AND = "and";
    public static final String OR = "or";

    public static final String IN = "in";

    @Data
    public static class SqlCondition {
        private String leftField;
        private String rightField;
        private String op;

        @Override
        public String toString() {
            if (IN.equals(op)) {
                return String.format("%s %s (%s)", leftField, op, rightField);
            } else {
                return String.format("%s %s %s", leftField, op, rightField);
            }
        }
    }

    public String condition(JSONObject json) {
        if (json.containsKey(AND)) {
            JSONArray andList = json.getJSONArray(AND);
            return condition(andList, true);
        }
        if (json.containsKey(OR)) {
            JSONArray orList = json.getJSONArray(OR);
            return condition(orList, false);
        }
        throw new RuntimeException("无效条件");
    }


    private String condition(JSONArray array, boolean isAnd) {
        List<String> subConditions = new ArrayList<>();
        for (Object obj : array) {
            if (obj instanceof JSONObject) {
                JSONObject item = (JSONObject) obj;
                if (item.containsKey(AND) || item.containsKey(OR)) {
                    subConditions.add(String.format("( %s )", condition(item)));
                } else {
                    SqlCondition sqlCondition = item.toJavaObject(SqlCondition.class);
                    subConditions.add(sqlCondition.toString());
                }
            }
        }
        if (isAnd) {
            return String.join(String.format(" %s ", AND), subConditions);
        } else {
            return String.join(String.format(" %s ", OR), subConditions);
        }
    }
}
